<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>酒花图鉴与融合实验室 (含风味雷达)</title>
    <!-- 引入 Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* :root 和 body 样式基本不变 */
        :root {
            --bg-color: #1E1E2E;
            --tile-bg-color: #2A2A3E;
            --tile-border-color: #4A4A5E;
            --tile-hover-bg-color: #3A3A4E;
            --tile-hover-border-color: #F7B731;
            --text-color: #D0D0FF;
            --title-color: #F7B731;
            --subtitle-color: #8A8AAF;
            --modal-bg-color: #252535;
            --modal-header-bg: #F7B731;
            --modal-header-text: #1E1E2E;
            --modal-border-color: #F7B731;
            --info-icon-color: #F7B731;
            --strong-text-color: #50FA7B;
            --fusion-slot-bg: #2E2E42;
            --fusion-slot-border: #5A5A7E;
            --fusion-slot-hover-border: #F7B731;
            --fusion-result-bg: #222232;
            --chart-bg-color: #2E2E42cc; /* 雷达图背景颜色 */
            --chart-grid-color: #5A5A7Ecc;
            --chart-label-color: #D0D0FF;
            --chart-point-color: #F7B731;
            --chart-line-color: #F7B731a0;
        }

        body {
            font-family: 'PixelatedFont', 'SimSun', 'NSimSun', 'Courier New', Courier, monospace;
            background-color: var(--bg-color);
            color: var(--text-color);
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            image-rendering: pixelated;
            /* ... (其他 image-rendering 前缀) ... */
        }

        /* ... (header-container, main-title, subtitle, content-wrapper, section-title 样式不变) ... */
         .header-container { text-align: center; margin-bottom: 20px; }
        .main-title { color: var(--title-color); font-size: 2.4em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 5px 0; text-shadow: 2px 2px #000000aa; border: 2px solid var(--title-color); display: inline-block; padding: 5px 15px; background-color: #00000033; }
        .subtitle { color: var(--subtitle-color); font-size: 0.9em; margin: 0; }
        .content-wrapper { width: 100%; max-width: 1200px; display: flex; flex-direction: column; gap: 30px; }
        .hop-dex-section, .fusion-lab-section { background-color: var(--tile-bg-color); border: 2px solid var(--tile-border-color); padding: 20px; border-radius: 6px; }
        .section-title { color: var(--title-color); font-size: 1.6em; text-align: center; margin-bottom: 20px; border-bottom: 2px dashed var(--tile-border-color); padding-bottom: 10px; }


        /* ... (hop-grid, hop-tile 样式不变) ... */
        .hop-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 10px; }
        .hop-tile { background-color: var(--tile-bg-color); border: 2px solid var(--tile-border-color); padding: 8px 6px; cursor: grab; text-align: center; transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.1s ease; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 85px; }
        .hop-tile:active { cursor: grabbing; }
        .hop-tile:hover { background-color: var(--tile-hover-bg-color); border-color: var(--tile-hover-border-color); transform: scale(1.05); }
        .hop-tile .hop-symbol { font-size: 1.6em; font-weight: bold; color: var(--title-color); margin-bottom: 3px; line-height: 1; pointer-events: none; }
        .hop-tile .hop-name-tile { font-size: 0.75em; color: var(--text-color); line-height: 1.1; word-break: break-word; pointer-events: none; }


        /* Fusion Lab Styles (基本不变) */
        .fusion-area { display: flex; flex-direction: column; align-items: center; gap: 20px; }
        .fusion-slots { display: flex; gap: 20px; margin-bottom: 15px; align-items: flex-start; /* Align items to the top */ }
        .fusion-slot { width: 140px; /* Slightly wider to accommodate radio buttons */ background-color: var(--fusion-slot-bg); border: 3px dashed var(--fusion-slot-border); border-radius: 6px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; /* Distribute space */ text-align: center; color: var(--subtitle-color); font-size: 0.8em; transition: border-color 0.2s ease, background-color 0.2s ease; padding: 10px 5px; min-height: 150px; /* Increased height */ }
        .fusion-slot.drag-over { border-color: var(--fusion-slot-hover-border); background-color: #383848; }
        .fusion-slot-hop-info { /* Container for symbol and name */ min-height: 60px; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; }
        .fusion-slot .slot-hop-symbol { font-size: 2em; font-weight: bold; color: var(--title-color); margin-bottom: 5px; }
        .fusion-slot .slot-hop-name { font-size: 0.9em; color: var(--text-color); }
        .fusion-slot-usage-type { margin-top: 10px; font-size: 0.85em; display: flex; flex-direction: column; gap: 5px; align-items: flex-start;}
        .fusion-slot-usage-type label { display: flex; align-items: center; cursor: pointer;}
        .fusion-slot-usage-type input[type="radio"] { margin-right: 5px; accent-color: var(--title-color); }


        .fusion-controls button { background-color: var(--title-color); color: var(--modal-header-text); border: none; padding: 10px 20px; font-family: inherit; font-size: 1em; cursor: pointer; border-radius: 4px; transition: background-color 0.15s ease; margin: 0 5px; }
        .fusion-controls button:hover { background-color: #d4a029; }
        .fusion-controls button:disabled { background-color: var(--tile-border-color); color: var(--subtitle-color); cursor: not-allowed; }
        .fusion-result-area { margin-top: 20px; padding: 15px; background-color: var(--fusion-result-bg); border: 2px solid var(--tile-border-color); border-radius: 6px; min-height: 80px; width: 100%; max-width: 500px; text-align: center; }
        .fusion-result-area h4 { color: var(--title-color); margin-top: 0; margin-bottom: 10px; }
        .fusion-result-area p { font-size: 0.9em; line-height: 1.5; margin: 5px 0; }
        .fusion-result-area strong { color: var(--strong-text-color); }


        /* Modal Styles 更新，增加雷达图容器 */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.75); align-items: center; justify-content: center; padding: 15px; box-sizing: border-box; }
        .modal-content { background-color: var(--modal-bg-color); border: 3px solid var(--modal-border-color); border-radius: 8px; width: 90%; max-width: 520px; /* 稍微加宽以容纳雷达图 */ box-shadow: 0px 0px 0px 3px #00000066, 0 5px 15px rgba(0,0,0,0.5); animation: slideIn 0.2s ease-out; overflow: hidden; }
        /* ... (modal-header, close-button, modal-body, modal-icon-area 样式不变) ... */
        .modal-header { background-color: var(--modal-header-bg); color: var(--modal-header-text); padding: 10px 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--modal-border-color); }
        .modal-header h2 { margin: 0; font-size: 1.3em; font-weight: bold; line-height: 1.3; }
        .close-button { font-size: 1.8em; font-weight: bold; color: var(--modal-header-text); background: none; border: 2px solid transparent; cursor: pointer; padding: 0 5px; line-height: 1; transition: color 0.15s ease, transform 0.1s ease; }
        .close-button:hover { color: #000000; transform: scale(1.1); }
        .modal-body { padding: 15px; display: flex; flex-direction: column; gap: 15px; max-height: 85vh; overflow-y: auto;} /* 允许内容滚动 */
        .modal-icon-area { background-color: var(--tile-bg-color); border: 2px solid var(--tile-border-color); width: 112px; height: 112px; margin: 0 auto; display: flex; align-items: center; justify-content: center; overflow: hidden; border-radius: 4px; }
        .modal-icon-area img { max-width: 100%; max-height: 100%; }


        .modal-info-section { border-top: 2px dashed var(--tile-border-color); padding-top: 15px; }
        .modal-info-section h3 { color: var(--title-color); margin-top: 0; margin-bottom: 12px; font-size: 1.2em; text-align: center; }
        .modal-info-section p { margin: 10px 0; font-size: 0.95em; line-height: 1.5; display: flex; align-items: flex-start; }
        .modal-info-section .info-icon { margin-right: 10px; color: var(--info-icon-color); font-size: 1.1em; min-width: 1.2em; padding-top: 2px; }
        .modal-info-section strong { color: var(--strong-text-color); margin-right: 5px; white-space: nowrap; }

        .radar-chart-container {
            margin-top: 15px;
            padding: 10px;
            background-color: var(--chart-bg-color);
            border: 1px solid var(--tile-border-color);
            border-radius: 4px;
        }
        .radar-chart-container h4 {
            color: var(--title-color);
            text-align: center;
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        /* 融合结果区域的雷达图容器 (如果需要单独显示) */
        .fusion-radar-container {
            margin-top: 15px;
            padding: 10px;
            background-color: var(--chart-bg-color);
            border: 1px solid var(--tile-border-color);
            border-radius: 4px;
            max-width: 350px; /* 控制融合雷达图大小 */
            margin-left: auto;
            margin-right: auto;
        }
         .fusion-radar-container h4 {
            color: var(--title-color);
            text-align: center;
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 1.1em;
        }
    </style>
</head>
<body>
    <div class="header-container">
        <h1 class="main-title">酒花图鉴与融合实验室</h1>
        <p class="subtitle">探索酒花奥秘，尝试风味融合！指定投放方式以获得更精确建议。</p>
    </div>

    <div class="content-wrapper">
        <section class="hop-dex-section">
            <h2 class="section-title">酒花图鉴 (拖动酒花到下方实验室)</h2>
            <div class="hop-grid" id="hopGrid">
                <!-- Hop tiles will be dynamically inserted here -->
            </div>
        </section>

        <section class="fusion-lab-section">
            <h2 class="section-title">酒花融合实验室</h2>
            <div class="fusion-area">
                <div class="fusion-slots">
                    <div class="fusion-slot" id="fusionSlot1" data-slot-id="1">
                        <div class="fusion-slot-hop-info">拖入酒花1</div>
                        <div class="fusion-slot-usage-type">
                            <label><input type="radio" name="slot1_usage" value="boil" checked> 熬煮</label>
                            <label><input type="radio" name="slot1_usage" value="dryhop"> 干投</label>
                        </div>
                    </div>
                    <div class="fusion-slot" id="fusionSlot2" data-slot-id="2">
                        <div class="fusion-slot-hop-info">拖入酒花2</div>
                        <div class="fusion-slot-usage-type">
                            <label><input type="radio" name="slot2_usage" value="boil" checked> 熬煮</label>
                            <label><input type="radio" name="slot2_usage" value="dryhop"> 干投</label>
                        </div>
                    </div>
                </div>
                <div class="fusion-controls">
                    <button id="fuseButton" disabled>开始融合</button>
                    <button id="clearButton">清空</button>
                </div>
                <div class="fusion-result-area" id="fusionResultArea">
                    <h4>融合建议</h4>
                    <p>请先将两种酒花拖入上方融合槽，并选择投放方式。</p>
                    <!-- 融合雷达图将动态添加到这里或下方 -->
                </div>
                <div class="fusion-radar-container" id="fusionRadarContainer" style="display: none;">
                    <h4>融合风味雷达</h4>
                    <canvas id="fusionRadarChart"></canvas>
                </div>
            </div>
        </section>
    </div>

    <!-- Modal Card (HTML 更新，增加雷达图 canvas) -->
    <div id="hopCardModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalHopNameFull">酒花名称 (Symbol)</h2>
                <span id="closeModalBtn" class="close-button">×</span>
            </div>
            <div class="modal-body">
                <div class="modal-icon-area">
                    <img id="modalHopIcon" src="" alt="酒花像素图标">
                </div>
                <div class="modal-info-section">
                    <h3 id="modalInfoTitle">酒花信息</h3>
                    <p><span class="info-icon">🌍</span><strong>产地/类型:</strong> <span id="modalOrigin"></span></p>
                    <p><span class="info-icon">👃</span><strong>香气/风味:</strong> <span id="modalAroma"></span></p>
                    <p><span class="info-icon">🌿</span><strong>Alpha 酸:</strong> <span id="modalAlpha"></span></p>
                    <p><span class="info-icon">🍺</span><strong>常见风格:</strong> <span id="modalStyles"></span></p>
                    <p><span class="info-icon">💡</span><strong>备注:</strong> <span id="modalNotes"></span></p>
                </div>
                <div class="radar-chart-container">
                    <h4>风味雷达图 (基准)</h4>
                    <canvas id="hopDetailRadarChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        const flavorDimensions = ['柑橘', '花香', '辛辣', '草本', '松针树脂', '热带水果', '泥土', '其他果香'];
        // const flavorDimensions_en = ['Citrus', 'Floral', 'Spicy', 'Herbal', 'Piney/Resinous', 'Tropical', 'Earthy', 'Fruity-Other'];

        // Flavor profile modifiers based on usage type
        // These are illustrative multipliers. Adjust them based on desired effect.
        // Values > 1 emphasize, < 1 de-emphasize.
        const usageModifiers = {
            boil: { // Late boil addition, retains some aroma but less than dry hop
                '柑橘': 0.8, '花香': 0.6, '辛辣': 1.0, '草本': 1.0, 
                '松针树脂': 1.1, '热带水果': 0.5, '泥土': 1.0, '其他果香': 0.7
            },
            dryhop: { // Maximizes volatile aromatics
                '柑橘': 1.2, '花香': 1.3, '辛辣': 0.9, '草本': 0.8, 
                '松针树脂': 0.8, '热带水果': 1.5, '泥土': 0.7, '其他果香': 1.4
            }
        };


        const hopsData = [
            {
                id: 1, symbol: "Si", name: "Simcoe", name_zh: "西姆科",
                origin: "美国 - 双用途酒花", aroma: "强烈的松针、西柚、百香果，伴有泥土和莓果气息。",
                alpha: "12-14%", styles: "IPA (西海岸IPA), APA, DIPA。", notes: "独特的松针和树脂特性。",
                icon: "simcoe_pixel_icon.png", keywords: ["松针", "西柚", "树脂", "苦"],
                flavorProfile: { '柑橘': 4, '花香': 1, '辛辣': 2, '草本': 2, '松针树脂': 5, '热带水果': 3, '泥土': 3, '其他果香': 2 }
            },
            {
                id: 2, symbol: "Ci", name: "Citra", name_zh: "奇楚果",
                origin: "美国 - 香型酒花", aroma: "柑橘(西柚、青柠)和热带水果(芒果、百香果、荔枝)。",
                alpha: "11-15%", styles: "IPA (NEIPA), APA。", notes: "爆炸性水果风味。",
                icon: "citra_pixel_icon.png", keywords: ["柑橘", "热带水果", "芒果", "百香果", "甜香"],
                flavorProfile: { '柑橘': 5, '花香': 1, '辛辣': 1, '草本': 0, '松针树脂': 1, '热带水果': 5, '泥土': 0, '其他果香': 4 }
            },
            {
                id: 3, symbol: "Mo", name: "Mosaic", name_zh: "马赛克",
                origin: "美国 - 香型酒花", aroma: "蓝莓、橘子、木瓜、玫瑰、青草、泡泡糖等。",
                alpha: "10-13%", styles: "IPA, APA。", notes: "“马赛克”般丰富多变。",
                icon: "mosaic_pixel_icon.png", keywords: ["蓝莓", "橘子", "热带水果", "复杂", "甜香"],
                flavorProfile: { '柑橘': 3, '花香': 2, '辛辣': 1, '草本': 2, '松针树脂': 2, '热带水果': 4, '泥土': 1, '其他果香': 5 }
            },
            {
                id: 4, symbol: "Sa", name: "Saaz", name_zh: "萨兹",
                origin: "捷克 - 贵族香型", aroma: "细腻的草本、花香和微弱的辛辣、泥土气息。",
                alpha: "2-5%", styles: "皮尔森, 拉格。", notes: "四大贵族酒花之一。",
                icon: "saaz_pixel_icon.png", keywords: ["草本", "花香", "辛辣", "泥土", "经典"],
                flavorProfile: { '柑橘': 0, '花香': 4, '辛辣': 3, '草本': 5, '松针树脂': 0, '热带水果': 0, '泥土': 3, '其他果香': 1 }
            },
            {
                id: 5, symbol: "Ga", name: "Galaxy", name_zh: "银河",
                origin: "澳大利亚 - 香型", aroma: "强烈的百香果、桃子、柑橘和菠萝等热带水果风味。",
                alpha: "13-16%", styles: "IPA (澳式, NEIPA), Pale Ale。", notes: "浓郁的热带水果香气。",
                icon: "galaxy_pixel_icon.png", keywords: ["百香果", "桃子", "热带水果", "强劲", "甜香"],
                flavorProfile: { '柑橘': 3, '花香': 1, '辛辣': 0, '草本': 0, '松针树脂': 1, '热带水果': 5, '泥土': 0, '其他果香': 4 }
            },
            {
                id: 6, symbol: "Cs", name: "Cascade", name_zh: "卡斯卡特",
                origin: "美国 - 香型酒花", aroma: "中等强度的花香、西柚等柑橘香气，带有些许辛辣感。",
                alpha: "4.5-7%", styles: "APA, 美式IPA。", notes: "美式精酿浪潮的奠基者。",
                icon: "cascade_pixel_icon.png", keywords: ["花香", "柑橘", "西柚", "经典"],
                flavorProfile: { '柑橘': 4, '花香': 3, '辛辣': 2, '草本': 1, '松针树脂': 2, '热带水果': 1, '泥土': 1, '其他果香': 1 }
            }
        ];

        let detailChartInstance = null;
        let fusionChartInstance = null;

        document.addEventListener('DOMContentLoaded', () => {
            const hopGrid = document.getElementById('hopGrid');
            const modal = document.getElementById('hopCardModal');
            const closeModalButton = document.getElementById('closeModalBtn');
            const modalHopNameFull = document.getElementById('modalHopNameFull');
            const modalHopIcon = document.getElementById('modalHopIcon');
            const modalOrigin = document.getElementById('modalOrigin');
            const modalAroma = document.getElementById('modalAroma');
            const modalAlpha = document.getElementById('modalAlpha');
            const modalStyles = document.getElementById('modalStyles');
            const modalNotes = document.getElementById('modalNotes');

            const fusionSlot1Element = document.getElementById('fusionSlot1');
            const fusionSlot2Element = document.getElementById('fusionSlot2');
            const fuseButton = document.getElementById('fuseButton');
            const clearButton = document.getElementById('clearButton');
            const fusionResultArea = document.getElementById('fusionResultArea');
            const fusionRadarContainer = document.getElementById('fusionRadarContainer');

            let draggedHopId = null;
            let selectedHop1 = null;
            let selectedHop2 = null;
            const placeholderIcon = "";

            hopsData.forEach(hop => {
                const tile = document.createElement('div');
                tile.classList.add('hop-tile');
                tile.dataset.hopId = hop.id;
                tile.draggable = true;
                const symbolEl = document.createElement('span');
                symbolEl.classList.add('hop-symbol');
                symbolEl.textContent = hop.symbol;
                const nameEl = document.createElement('span');
                nameEl.classList.add('hop-name-tile');
                nameEl.textContent = hop.name_zh;
                tile.appendChild(symbolEl);
                tile.appendChild(nameEl);
                hopGrid.appendChild(tile);
                tile.addEventListener('click', (event) => {
                    if (event.detail === 0) return; // Avoid conflict with drag
                    displayHopDetailModal(hop.id);
                });
                tile.addEventListener('dragstart', (event) => {
                    draggedHopId = hop.id;
                    event.dataTransfer.setData('text/plain', hop.id);
                    event.target.style.opacity = '0.5';
                });
                tile.addEventListener('dragend', (event) => {
                    event.target.style.opacity = '1';
                    draggedHopId = null;
                });
            });

            function displayHopDetailModal(hopId) {
                const hop = hopsData.find(h => h.id === hopId);
                if (!hop) return;
                modalHopNameFull.textContent = `${hop.name_zh} (${hop.name} - ${hop.symbol})`;
                // ... (rest of modal info remains same)
                modalOrigin.textContent = hop.origin;
                modalAroma.textContent = hop.aroma;
                modalAlpha.textContent = hop.alpha;
                modalStyles.textContent = hop.styles;
                modalNotes.textContent = hop.notes || "暂无备注";
                const iconPath = `icons/${hop.icon}`; // Ensure you have an icons folder
                modalHopIcon.src = iconPath;
                modalHopIcon.onerror = () => { modalHopIcon.src = placeholderIcon; };


                if (hop.flavorProfile) {
                    const radarData = flavorDimensions.map(dim => hop.flavorProfile[dim] || 0);
                    createOrUpdateRadarChart('hopDetailRadarChart', radarData, `${hop.name_zh} (基准)`, detailChartInstance, (newInstance) => { detailChartInstance = newInstance; });
                } else {
                    if (detailChartInstance) {
                        detailChartInstance.destroy();
                        detailChartInstance = null;
                    }
                     document.getElementById('hopDetailRadarChart').getContext('2d').clearRect(0, 0, document.getElementById('hopDetailRadarChart').width, document.getElementById('hopDetailRadarChart').height);
                }
                modal.style.display = 'flex';
            }
            closeModalButton.addEventListener('click', () => { modal.style.display = 'none'; });
            window.addEventListener('click', (event) => { if (event.target === modal) modal.style.display = 'none'; });
            window.addEventListener('keydown', (event) => { if (event.key === 'Escape' && modal.style.display === 'flex') modal.style.display = 'none';});


            [fusionSlot1Element, fusionSlot2Element].forEach(slotElement => {
                slotElement.addEventListener('dragover', (event) => { event.preventDefault(); slotElement.classList.add('drag-over'); });
                slotElement.addEventListener('dragleave', () => { slotElement.classList.remove('drag-over'); });
                slotElement.addEventListener('drop', (event) => {
                    event.preventDefault();
                    slotElement.classList.remove('drag-over');
                    const hopId = parseInt(event.dataTransfer.getData('text/plain'));
                    const hop = hopsData.find(h => h.id === hopId);
                    if (hop) {
                        if (slotElement.id === 'fusionSlot1') selectedHop1 = hop;
                        else selectedHop2 = hop;
                        updateSlotDisplay(slotElement, hop);
                        checkFusionButtonState();
                    }
                });
            });

            function updateSlotDisplay(slotElement, hop) {
                const hopInfoDiv = slotElement.querySelector('.fusion-slot-hop-info');
                if (hop) {
                    hopInfoDiv.innerHTML = `<span class="slot-hop-symbol">${hop.symbol}</span><span class="slot-hop-name">${hop.name_zh}</span>`;
                } else {
                    const slotId = slotElement.dataset.slotId;
                    hopInfoDiv.innerHTML = `拖入酒花${slotId}`;
                }
            }
            function checkFusionButtonState() {
                 fuseButton.disabled = !(selectedHop1 && selectedHop2);
            }

            fuseButton.addEventListener('click', () => {
                if (selectedHop1 && selectedHop2) {
                    const usageType1 = document.querySelector('input[name="slot1_usage"]:checked').value;
                    const usageType2 = document.querySelector('input[name="slot2_usage"]:checked').value;

                    const result = calculateFusion(selectedHop1, selectedHop2, usageType1, usageType2);
                    displayFusionResult(result.text);

                    if (selectedHop1.flavorProfile && selectedHop2.flavorProfile) {
                        const modifiedProfile1 = getModifiedFlavorProfile(selectedHop1, usageType1);
                        const modifiedProfile2 = getModifiedFlavorProfile(selectedHop2, usageType2);
                        
                        const fusedProfileData = averageProfiles(modifiedProfile1, modifiedProfile2);
                        
                        createOrUpdateRadarChart('fusionRadarChart', fusedProfileData, `融合风味 (${usageType1}/${usageType2})`, fusionChartInstance, (newInstance) => { fusionChartInstance = newInstance; });
                        fusionRadarContainer.style.display = 'block';
                    } else {
                        fusionRadarContainer.style.display = 'none';
                        if (fusionChartInstance) {
                            fusionChartInstance.destroy(); fusionChartInstance = null;
                        }
                    }
                }
            });

            clearButton.addEventListener('click', () => {
                selectedHop1 = null;
                selectedHop2 = null;
                updateSlotDisplay(fusionSlot1Element, null);
                updateSlotDisplay(fusionSlot2Element, null);
                
                // Reset radio buttons to default (boil)
                document.querySelector('input[name="slot1_usage"][value="boil"]').checked = true;
                document.querySelector('input[name="slot2_usage"][value="boil"]').checked = true;

                fusionResultArea.innerHTML = `<h4>融合建议</h4><p>请先将两种酒花拖入上方融合槽，并选择投放方式。</p>`;
                fusionRadarContainer.style.display = 'none';
                 if (fusionChartInstance) {
                    fusionChartInstance.destroy(); fusionChartInstance = null;
                }
                checkFusionButtonState();
            });

            function getModifiedFlavorProfile(hop, usageType) {
                if (!hop.flavorProfile) return flavorDimensions.map(() => 0); // Return zeros if no base profile

                const baseProfile = hop.flavorProfile;
                const modifiers = usageModifiers[usageType] || {}; // Get specific modifiers or empty if type unknown
                
                let modifiedValues = flavorDimensions.map(dim => {
                    const baseValue = baseProfile[dim] || 0;
                    const modifier = modifiers[dim] || 1; // Default to 1 (no change) if dimension not in modifiers
                    let modified = baseValue * modifier;
                    return Math.max(0, Math.min(5, modified)); // Clamp between 0 and 5
                });
                return modifiedValues;
            }

            function averageProfiles(profileData1, profileData2) {
                return profileData1.map((val, index) => (val + profileData2[index]) / 2);
            }


            function calculateFusion(hop1, hop2, usage1, usage2) {
                let suggestion = "";
                suggestion += `<p>您选择了 <strong>${hop1.name_zh}</strong> (${usage1 === 'boil' ? '熬煮' : '干投'}) 和 <strong>${hop2.name_zh}</strong> (${usage2 === 'boil' ? '熬煮' : '干投'})。</p>`;
                
                const keywords1 = usage1 === 'dryhop' ? [...hop1.keywords, "芳香突出"] : hop1.keywords;
                const keywords2 = usage2 === 'dryhop' ? [...hop2.keywords, "芳香突出"] : hop2.keywords;
                let combinedKeywords = new Set([...keywords1, ...keywords2]);
                let keywordsArray = Array.from(combinedKeywords);

                suggestion += `<p>它们共同可能带来：<strong>${keywordsArray.join("、")}</strong> 等风味特点。</p>`;

                // Enhanced textual suggestions based on usage
                if (usage1 === 'dryhop' && usage2 === 'dryhop') {
                    suggestion += `<p>风味策略：双重干投将带来<strong>极致的芳香体验</strong>，适合NEIPA或香气主导的酒款。</p>`;
                } else if (usage1 === 'boil' && usage2 === 'dryhop' || usage1 === 'dryhop' && usage2 === 'boil') {
                    suggestion += `<p>风味策略：熬煮与干投结合，可以实现<strong>风味的层次感</strong>，苦度与香气并存。</p>`;
                } else { // both boil
                    suggestion += `<p>风味策略：两者都用于熬煮，将侧重于麦汁煮沸过程中赋予的<strong>基础风味和苦度</strong>。</p>`;
                }

                if (keywordsArray.includes("柑橘") && keywordsArray.includes("松针") && (usage1 === 'boil' || usage2 === 'boil')) {
                    suggestion += `<p>风格联想：可能适合酿造一款经典的<strong>西海岸IPA</strong>，尤其是当熬煮酒花提供坚实苦度时。</p>`;
                } else if (keywordsArray.filter(k => ["热带水果", "芒果", "百香果", "甜香", "橘子", "芳香突出"].includes(k)).length >= 2 && (usage1 === 'dryhop' || usage2 === 'dryhop')) {
                    suggestion += `<p>风格联想：非常适合酿造<strong>NEIPA (浑浊IPA)</strong>，利用干投最大化果香。</p>`;
                } else if (keywordsArray.includes("草本") && keywordsArray.includes("花香") && keywordsArray.includes("经典")) {
                    suggestion += `<p>风格联想：适合酿造优雅的<strong>皮尔森</strong>或<strong>传统拉格</strong>，熬煮为主。</p>`;
                } else if (keywordsArray.includes("柑橘") && keywordsArray.includes("花香")) {
                     suggestion += `<p>风格联想：适合酿造一款香气愉悦的<strong>美式淡色艾尔 (APA)</strong>。</p>`;
                } else if ((hop1.name === "Citra" && hop2.name === "Mosaic" || hop1.name === "Mosaic" && hop2.name === "Citra") && (usage1 === 'dryhop' || usage2 === 'dryhop')) {
                    suggestion += `<p>风格联想：现代<strong>IPA/NEIPA</strong>的黄金芳香搭档！</p>`;
                } else {
                    suggestion += `<p>风格联想：这是一个有趣的组合，值得尝试！</p>`;
                }

                let alpha1 = usage1 === 'boil' ? parseFloat(hop1.alpha) || 0 : 0;
                let alpha2 = usage2 === 'boil' ? parseFloat(hop2.alpha) || 0 : 0;
                let effectiveAlphaSum = alpha1 + alpha2;
                let boilHopCount = (usage1 === 'boil' ? 1:0) + (usage2 === 'boil' ? 1:0);
                let avgAlpha = boilHopCount > 0 ? effectiveAlphaSum / boilHopCount : 0;

                if (boilHopCount > 0) {
                    suggestion += `<p>熬煮苦度潜力：${avgAlpha > 0 ? (avgAlpha > 8 ? (avgAlpha > 12 ? '偏高':'中等') : '偏低') : '低'} (基于熬煮酒花的Alpha酸均值)。</p>`;
                } else {
                    suggestion += `<p>熬煮苦度潜力：低 (主要为干投，苦度贡献可忽略)。</p>`;
                }
                if (usage1 === 'dryhop' || usage2 === 'dryhop') {
                     suggestion += `<p>干投将显著提升啤酒的<strong>香气复杂度</strong>。</p>`;
                }

                return { text: suggestion };
            }

            function displayFusionResult(resultHTML) {
                fusionResultArea.innerHTML = `<h4>融合建议</h4>${resultHTML}`;
            }

            function createOrUpdateRadarChart(canvasId, data, label, chartInstance, setInstanceCallback) {
                const ctx = document.getElementById(canvasId).getContext('2d');
                if (chartInstance) {
                    chartInstance.data.datasets[0].data = data;
                    chartInstance.data.datasets[0].label = label;
                    chartInstance.update();
                } else {
                    const newInstance = new Chart(ctx, {
                        type: 'radar',
                        data: {
                            labels: flavorDimensions,
                            datasets: [{
                                label: label,
                                data: data,
                                fill: true,
                                backgroundColor: 'rgba(247, 183, 49, 0.2)',
                                borderColor: 'rgb(247, 183, 49)',
                                pointBackgroundColor: 'rgb(247, 183, 49)',
                                pointBorderColor: '#fff',
                                pointHoverBackgroundColor: '#fff',
                                pointHoverBorderColor: 'rgb(247, 183, 49)',
                                borderWidth: 1.5
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: true,
                            elements: { line: { borderWidth: 2 }},
                            scales: {
                                r: {
                                    angleLines: { display: true, color: 'rgba(208, 208, 255, 0.3)' },
                                    grid: { color: 'rgba(208, 208, 255, 0.3)' },
                                    pointLabels: {
                                        color: 'rgb(208, 208, 255)',
                                        font: { family: "'PixelatedFont', 'SimSun', 'NSimSun', 'Courier New', Courier, monospace", size: 10 }
                                    },
                                    ticks: {
                                        color: 'rgb(208, 208, 255, 0.7)', backdropColor: 'rgba(0,0,0,0)',
                                        stepSize: 1, font: { size: 8 }
                                    },
                                    suggestedMin: 0, suggestedMax: 5
                                }
                            },
                            plugins: {
                                legend: {
                                    display: true, position: 'top',
                                    labels: {
                                        color: 'rgb(208, 208, 255)',
                                        font: { family: "'PixelatedFont', 'SimSun', 'NSimSun', 'Courier New', Courier, monospace", size: 11 }
                                    }
                                }
                            }
                        }
                    });
                    if (setInstanceCallback) setInstanceCallback(newInstance);
                }
            }
            checkFusionButtonState();
        });
    </script>
</body>
</html>